import os
import subprocess

from util.comm.msg_util import msg


def cmdRun(cmd, is_msg=True, coding='gbk'):
    result = subprocess.run(['cmd', '/c', cmd], shell=True, capture_output=True)
    output = result.stdout.decode(coding)
    error = result.stderr.decode(coding)
    if error:
        if is_msg:
            msg("命令【%s】执行错误：%s" % (cmd, error))
        return None
    else:
        return output

def wrapCmd(cmd, is_shell=True, is_msg=True, coding='gbk'):
    if not is_shell or ~is_shell:
        subprocess.run(cmd)
        return

    result = subprocess.run(cmd, shell=is_shell, capture_output=True)
    error = result.stderr.decode(coding)
    if error:
        if is_msg:
            # 抛出执行异常
            raise Exception("命令【%s】执行错误：%s" % (cmd, error))

def wrapFunc(func, is_msg=True, coding='gbk'):
    result = func()
    error = result.stderr.decode(coding)
    if error:
        if is_msg:
            # 抛出执行异常
            raise Exception("执行错误：%s" % error)

if __name__ == '__main__':
    cmd = f"D:\\java\\code\\code-k\\python\\py-tool-ui\\util\\database\\redis-cli.exe -h 10.3.87.63 -p 7003 del sys_serviceconfig"
    wrapFunc(lambda c=cmd: os.popen(c))
    print("over")

def wrap_with_try_except(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            try:
                msg("程序执行异常：%s" % e)
            except Exception as ee:
                print("------程序执行异常：%s" % e)
                msg("程序执行异常")

    return wrapper
